import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { CreateAvatarDto } from './dto/create-avatar.dto'
import { Repository } from 'typeorm'
import { Avatar } from './entities/avatar.entity'

@Injectable()
export class AvatarService {
  constructor(@InjectRepository(Avatar) private readonly avatar: Repository<Avatar>) {}

  async create(file: Express.Multer.File, createAvatarDto: CreateAvatarDto) {
    if (!file) throw new BadRequestException('文件未上传')
    if (!createAvatarDto || !createAvatarDto.user_id) throw new BadRequestException('用户ID不能为空')
    try {
      const res = await this.avatar.findOne({
        where: { user_id: createAvatarDto.user_id }
      })
      if (res) throw new BadRequestException('用户ID已存在,禁止上传!')

      const avatar = new Avatar()
      avatar.user_id = createAvatarDto.user_id
      avatar.avatar = file.buffer
      avatar.contentType = file.mimetype
      await this.avatar.save(avatar)
      return { data: '', message: '上传成功!' }
    } catch (error) {
      throw new BadRequestException(error.message)
    }
  }

  async findOne(uid: string) {
    try {
      return await this.avatar.findOne({
        where: { user_id: uid }
      })
    } catch (error) {
      throw new BadRequestException(error.message)
    }
  }

  async changeAvatar(file: Express.Multer.File, uid: string) {
    if (!file) throw new BadRequestException('文件未上传')
    try {
      const avatar = await this.avatar.findOneBy({ user_id: uid })
      if (!avatar) throw new NotFoundException('用户未找到!')
      avatar.avatar = file.buffer
      await this.avatar.save(avatar)
      return { data: { userID: uid }, message: '修改成功!' }
    } catch (error) {
      throw new BadRequestException(error.message)
    }
  }
}
